package com.lhq.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lhq.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author zbhing
 * @description Mybatis-plus
 */
@Component
public class MpMetaObjectHandler implements MetaObjectHandler {
    private static final Logger log = LoggerFactory.getLogger(MpMetaObjectHandler.class);
    private static final String CREATE_TIME = "createTime";
    private static final String CREATE_BY = "createBy";
    private static final String UPDATE_TIME = "updateTime";
    private static final String UPDATE_BY = "updateBy";

    private static final String DEL_FLAG = "delFlag";

    /**
     * @method 插入时自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("插入时自动填充");
        this.strictInsertFill(metaObject,DEL_FLAG,Integer.class,0);
        this.strictInsertFill(metaObject,CREATE_BY,String.class,getUserId());
        this.strictInsertFill(metaObject,UPDATE_BY,String.class,getUserId());
        this.strictInsertFill(metaObject,CREATE_TIME,Date.class,new Date());
        this.strictInsertFill(metaObject,UPDATE_TIME,Date.class,new Date());
    }

    /**
     * @method 更新时自动填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("更新时自动填充");
        this.strictUpdateFill(metaObject,UPDATE_TIME,Date.class,new Date());
        this.strictUpdateFill(metaObject,UPDATE_BY,String.class,getUserId());
    }


    /**
     * 获取登录用户Id 作为create_by & update_by
     * @return userId
     */
    private String getUserId() {
        try {
            return SecurityUtils.getLoginUser().getUsername();
        }catch (Exception e) {
            return "";
        }
    }
}
